﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using KorleBu.Application_Classes;

namespace KorleBu
{
    public partial class ReceivedLog : System.Web.UI.Page
    {
        #region Class State Variables
        DataSet ds = new DataSet();
        Presentation presentation = new Presentation();
        public DataSet items = new DataSet();

        static int RequisitionID; 
        #endregion

        ////Jason Vance 10-31-12; Lazy initialize the label found on MasterPage.Master
        //private Label _lblMasterError;
        //private Label lblMasterError
        //{
        //    get
        //    {
        //        if (_lblMasterError == null)
        //            _lblMasterError = (Label)Master.FindControl("lblMasterError");
        //        return _lblMasterError;
        //    }
        //}

        #region Page Load
        protected void Page_Load(object sender, EventArgs e)
        {
            lblMasterError.Text = "";
            lblLoggedInUser.Text = "You are logged in as " + GetFirstName() + " " + GetLastName();
            if (!IsPostBack)
            {
                RequisitionID = Convert.ToInt32(Session["RequisitionID"].ToString());
                //Session.Remove("RequisitionID");
                ds = presentation.GetRequisitionItemsByRequisitionID(RequisitionID, false);

                if (ds.Tables[0].Rows[0][0].ToString() == "")
                {
                    gvRequisition.DataSource = ds.Tables[1];
                    gvRequisition.DataBind();
                }
                else
                    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();

                //ds = presentation.GetReceiptVoucher(RequisitionID);

                //if (ds.Tables[0].Rows[0][0].ToString() == "")
                //{
                //    gvReceiptVoucher.DataSource = ds.Tables[1];
                //    gvReceiptVoucher.DataBind();
                //}
                ds = presentation.GetVendors();
                if (ds.Tables[0].Rows[0][0].ToString() == "")
                {
                    ddlSelectVendor.DataSource = ds.Tables[1];
                    ddlSelectVendor.DataTextField = "VendorName";
                    ddlSelectVendor.DataValueField = "VendorID";
                    ddlSelectVendor.DataBind();
                }
            }

            ds = presentation.GetReceiptVoucher(RequisitionID);

            if (ds.Tables[0].Rows[0][0].ToString() == "")
            {
                if (ds.Tables[1].Rows.Count > 0)
                {
                    String lpo = ds.Tables[1].Rows[0]["LPO"].ToString();
                    txtLPONo.Text = lpo;
                    String vendorid = ds.Tables[1].Rows[0]["VendorID"].ToString();
                    ddlSelectVendor.SelectedValue = vendorid;
                    String recOfficer = ds.Tables[1].Rows[0]["ReceivingOfficer"].ToString();
                    txtOfficer.Text = recOfficer;
                }
            }
            else
                lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();

            ds = presentation.GetStoreByID(GetStoreID());
            lblStoreDisplay.Text = ds.Tables[1].Rows[0][1].ToString();

            //ds = presentation.GetVendorByID(Convert.ToInt32(ddlSelectVendor.SelectedValue));

            //if (ds.Tables[0].Rows[0][0].ToString() == "")
            //{
            //    lblRLSupplier2.Text = ds.Tables[1].Rows[0][1].ToString();
            //    lblRLSupplierAddress2.Text = ds.Tables[1].Rows[0][2].ToString();
            //}
            //else
            //    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();
            
            #region Aarons stuff
            ////show a message for pending tasks if the given user has tasks to do.  
            ////This should only apply to store managers, general managers, CEOs, and Procurement
            ////show a message for pending tasks if the given user has tasks to do.  
            ////This should only apply to store managers, general managers, CEOs, and Procurement
            //if (Global.loggedInUser.getIsStoreManager())
            //{
            //    ds = presentation.GetPendingRequests(Global.loggedInUser.getStoreId());
            //    if (ds.Tables.Count > 0) // If the method returned successfully
            //    {
            //        if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
            //        {
            //            lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
            //        }
            //        else
            //        {
            //            lblSideBarContent.Text = "**You have pending satellite store requests to handle.**";
            //        }
            //    }
            //}
            //else if (Global.loggedInUser.getIsGeneralManager())
            //{
            //    ds = presentation.GetRequisitionsByPendingStatus();
            //    if (ds.Tables.Count > 0) // If the method returned successfully
            //    {
            //        if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
            //        {
            //            lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
            //        }
            //        else
            //        {
            //            lblSideBarContent.Text = "**You have pending requisitions to handle.**";
            //        }
            //    }
            //}
            //else if (Global.loggedInUser.getIsCEO())
            //{
            //    ds = presentation.GetRequisitionsByGMStatus();
            //    if (ds.Tables.Count > 0) // If the method returned successfully
            //    {
            //        if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
            //        {
            //            lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
            //        }
            //        else
            //        {
            //            lblSideBarContent.Text = "**You have pending requisitions to handle.**";
            //        }
            //    }
            //}
            //else if (Global.loggedInUser.getIsProcurement())
            //{
            //    ds = presentation.GetRequisitionsByCEOStatus();
            //    if (ds.Tables.Count > 0) // If the method returned successfully
            //    {
            //        if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
            //        {
            //            lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
            //        }
            //        else
            //        {
            //            lblSideBarContent.Text = "**You have pending requisition orders to handle.**";
            //        }
            //    }
            //}
            #endregion
        }
        #endregion

        #region Methods
        protected void gvRequisition_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Fill")
            {
                Page.Validate();
                if (!Page.IsValid)
                    return;

                //int index = Convert.ToInt32(e.CommandArgument);

                GridViewRow row = ((Button)e.CommandSource).Parent.Parent as GridViewRow;

                String fillQty = ((TextBox)row.FindControl("txtFill")).Text;
                int ordered = Convert.ToInt32(row.Cells[1].Text);
                if (fillQty == "" || Convert.ToInt32(fillQty) <= 0)
                {
                    lblMasterError.Text = "Must enter a valid fill quantity.";
                    return;
                }

                int fill = Convert.ToInt32(((TextBox)row.FindControl("txtFill")).Text);
                int vendorID = Convert.ToInt32(ddlSelectVendor.SelectedValue);
                int lpo = Convert.ToInt32(txtLPONo.Text);
                String recOfficer = txtOfficer.Text;

                int recieved = Convert.ToInt32(row.Cells[2].Text);

                if (ordered >= fill + recieved)
                {
                    ds = presentation.UpdateItemQuantityReceived(RequisitionID, Convert.ToInt32((row.FindControl("lblItemID") as Label).Text), fill, vendorID, lpo, recOfficer);

                    if (ds.Tables[0].Rows[0][0].ToString() == "")
                    {
                        ((TextBox)row.FindControl("txtFill")).Text = "";

                        ds = presentation.GetRequisitionItemsByRequisitionID(RequisitionID, false);
                        gvRequisition.DataSource = ds.Tables[1];
                        gvRequisition.DataBind();
                    }
                    else
                    {
                        lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();
                        ds = presentation.GetRequisitionItemsByRequisitionID(RequisitionID, false);
                        gvRequisition.DataSource = ds.Tables[1];
                        gvRequisition.DataBind();
                    }
                }
                else
                {
                    lblMasterError.Text = "Cannot fill more than was ordered.";
                }
            }
        }

        /// <summary>
        /// Evaluates how many items were ordered and received and disables the fill button if they are equal.
        /// </summary>
        /// <param name="ordered">How many items were ordered.</param>
        /// <param name="received">How many items were filled so far.</param>
        /// <returns>Enable/Disable the fill button Boolean.</returns>
        public Boolean ShouldFill(Object ordered, Object received)
        {
            Boolean rv = true;

            int iOrdered = Convert.ToInt32(ordered);
            int iReceived = Convert.ToInt32(received);

            if (iOrdered == iReceived)
                rv = false;

            return rv;
        }

        #endregion

        #region Buttons
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            presentation.CompleteRequisition(RequisitionID);
            Session.Remove("RequisitionID");
            Response.Redirect("RequisitionStoreManager.aspx");
        }

        protected void btnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("RequisitionStoreManager.aspx");
        }

        //protected void btnApply_LPO(object sender, EventArgs e)
        //{
        //    ds = presentation.UpdateLPO(RequisitionID, txtLPONo.Text.ToString());   
        //}

        //protected void btnApply_SRA(object sender, EventArgs e)
        //{
        //    if (txtSRA1.Text.ToString() != "")
        //        ds = presentation.UpdateSRA(RequisitionID, 1, txtSRA1.Text.ToString());
        //    if (txtSRA2.Text.ToString() != "")
        //        ds = presentation.UpdateSRA(RequisitionID, 2, txtSRA2.Text.ToString());
        //    if (txtSRA3.Text.ToString() != "")
        //        ds = presentation.UpdateSRA(RequisitionID, 3, txtSRA3.Text.ToString());
        //    if (txtSRA4.Text.ToString() != "")
        //        ds = presentation.UpdateSRA(RequisitionID, 4, txtSRA4.Text.ToString());
        //}
        #endregion

        #region Session Methods
        private int GetStoreID()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getStoreId();
        }
        private string GetFirstName()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getFirstName();
        }
        private string GetLastName()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getLastName();
        }
        private string GetSessionID()
        {
            try
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getSessionId();
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                return null;
            }
        }
        private bool GetIsAdmin()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsAdmin();
        }
        private bool GetIsGeneralManager()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsGeneralManager();
        }
        private bool GetIsStoreManager()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsStoreManager();
        }
        private bool GetIsStoreKeeper()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsStoreKeeper();
        }
        private bool GetIsSubUnitClerk()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsSubUnitClerk();
        }
        private bool GetIsAccounting()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsAccounting();
        }
        private bool GetIsProcurement()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsProcurement();
        }
        private bool GetIsCEO()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsCEO();
        }
        #endregion
    }
}